import { ElMessage, ElNotification } from 'element-plus'
import { useUserStore } from '@/stores/user'

class WebSocketClient {
  constructor() {
    this.ws = null
    this.reconnectAttempts = 0
    this.maxReconnectAttempts = 5
    this.reconnectInterval = 3000
    this.heartbeatInterval = 30000
    this.heartbeatTimer = null
    this.isConnected = false
    this.messageHandlers = new Map()
    this.userStore = null
  }

  /**
   * 连接WebSocket
   */
  connect(token) {
    if (!token) {
      console.warn('WebSocket连接失败: 缺少token')
      return
    }

    try {
      const wsUrl = `ws://localhost:8080/ws?token=${encodeURIComponent(token)}`
      this.ws = new WebSocket(wsUrl)
      
      this.ws.onopen = this.onOpen.bind(this)
      this.ws.onmessage = this.onMessage.bind(this)
      this.ws.onclose = this.onClose.bind(this)
      this.ws.onerror = this.onError.bind(this)
      
      console.log('WebSocket连接中...')
    } catch (error) {
      console.error('WebSocket连接失败:', error)
      this.scheduleReconnect()
    }
  }

  /**
   * 连接成功
   */
  onOpen(event) {
    console.log('WebSocket连接成功')
    this.isConnected = true
    this.reconnectAttempts = 0
    this.startHeartbeat()
    
    // 触发连接成功事件
    this.emit('connected', event)
  }

  /**
   * 接收消息
   */
  onMessage(event) {
    try {
      const message = JSON.parse(event.data)
      console.log('收到WebSocket消息:', message)
      
      this.handleMessage(message)
    } catch (error) {
      console.error('解析WebSocket消息失败:', error)
    }
  }

  /**
   * 连接关闭
   */
  onClose(event) {
    console.log('WebSocket连接关闭:', event.code, event.reason)
    this.isConnected = false
    this.stopHeartbeat()
    
    // 触发连接关闭事件
    this.emit('disconnected', event)
    
    // 如果不是主动关闭，尝试重连
    if (event.code !== 1000) {
      this.scheduleReconnect()
    }
  }

  /**
   * 连接错误
   */
  onError(error) {
    console.error('WebSocket连接错误:', error)
    this.emit('error', error)
  }

  /**
   * 处理接收到的消息
   */
  handleMessage(message) {
    const { type } = message
    
    switch (type) {
      case 'heartbeat':
        // 心跳响应，不需要处理
        break
        
      case 'chat':
        this.handleChatMessage(message)
        break
        
      case 'notification':
        this.handleNotification(message)
        break
        
      case 'announcement':
        this.handleAnnouncement(message)
        break
        
      case 'orderUpdate':
        this.handleOrderUpdate(message)
        break
        
      case 'system':
        this.handleSystemMessage(message)
        break
        
      default:
        console.warn('未知消息类型:', type)
    }
    
    // 触发通用消息事件
    this.emit('message', message)
    this.emit(type, message)
  }

  /**
   * 处理聊天消息
   */
  handleChatMessage(message) {
    const { fromUserId, content } = message
    
    // 显示消息通知
    ElNotification({
      title: '新消息',
      message: `来自 ${fromUserId}: ${content}`,
      type: 'info',
      duration: 5000
    })
  }

  /**
   * 处理通知消息
   */
  handleNotification(message) {
    const { title, content, notificationType } = message
    
    ElNotification({
      title: title || '通知',
      message: content,
      type: notificationType === 'error' ? 'error' : 'info',
      duration: 5000
    })
  }

  /**
   * 处理公告消息
   */
  handleAnnouncement(message) {
    const { title, content } = message
    
    ElNotification({
      title: title || '系统公告',
      message: content,
      type: 'warning',
      duration: 8000
    })
  }

  /**
   * 处理订单更新
   */
  handleOrderUpdate(message) {
    const { orderId, status, message: updateMessage } = message
    
    ElNotification({
      title: '订单更新',
      message: `订单 ${orderId} ${updateMessage}`,
      type: 'success',
      duration: 5000
    })
  }

  /**
   * 处理系统消息
   */
  handleSystemMessage(message) {
    const { content } = message
    
    ElMessage({
      message: content,
      type: 'info',
      duration: 3000
    })
  }

  /**
   * 发送消息
   */
  send(message) {
    if (!this.isConnected || !this.ws) {
      console.warn('WebSocket未连接，无法发送消息')
      return false
    }
    
    try {
      const messageStr = typeof message === 'string' ? message : JSON.stringify(message)
      this.ws.send(messageStr)
      return true
    } catch (error) {
      console.error('发送WebSocket消息失败:', error)
      return false
    }
  }

  /**
   * 发送心跳
   */
  sendHeartbeat() {
    this.send({
      type: 'heartbeat',
      timestamp: Date.now()
    })
  }

  /**
   * 开始心跳
   */
  startHeartbeat() {
    this.stopHeartbeat()
    this.heartbeatTimer = setInterval(() => {
      this.sendHeartbeat()
    }, this.heartbeatInterval)
  }

  /**
   * 停止心跳
   */
  stopHeartbeat() {
    if (this.heartbeatTimer) {
      clearInterval(this.heartbeatTimer)
      this.heartbeatTimer = null
    }
  }

  /**
   * 安排重连
   */
  scheduleReconnect() {
    if (this.reconnectAttempts >= this.maxReconnectAttempts) {
      console.error('WebSocket重连次数超过限制，停止重连')
      return
    }
    
    this.reconnectAttempts++
    console.log(`WebSocket将在 ${this.reconnectInterval}ms 后进行第 ${this.reconnectAttempts} 次重连`)
    
    setTimeout(() => {
      if (!this.userStore) {
        this.userStore = useUserStore()
      }
      
      const token = this.userStore.token
      if (token) {
        this.connect(token)
      }
    }, this.reconnectInterval)
  }

  /**
   * 关闭连接
   */
  close() {
    this.stopHeartbeat()
    
    if (this.ws) {
      this.ws.close(1000, 'Client closed')
      this.ws = null
    }
    
    this.isConnected = false
  }

  /**
   * 添加消息处理器
   */
  on(event, handler) {
    if (!this.messageHandlers.has(event)) {
      this.messageHandlers.set(event, [])
    }
    this.messageHandlers.get(event).push(handler)
  }

  /**
   * 移除消息处理器
   */
  off(event, handler) {
    if (this.messageHandlers.has(event)) {
      const handlers = this.messageHandlers.get(event)
      const index = handlers.indexOf(handler)
      if (index > -1) {
        handlers.splice(index, 1)
      }
    }
  }

  /**
   * 触发事件
   */
  emit(event, data) {
    if (this.messageHandlers.has(event)) {
      this.messageHandlers.get(event).forEach(handler => {
        try {
          handler(data)
        } catch (error) {
          console.error('事件处理器执行失败:', error)
        }
      })
    }
  }

  /**
   * 获取连接状态
   */
  getConnectionState() {
    return {
      isConnected: this.isConnected,
      reconnectAttempts: this.reconnectAttempts,
      readyState: this.ws ? this.ws.readyState : WebSocket.CLOSED
    }
  }
}

// 创建全局WebSocket实例
const webSocketClient = new WebSocketClient()

export default webSocketClient
